package org.blog.controller;

import org.blog.entity.Message;
import org.blog.entity.param.MessageParam;
import org.blog.service.MessageService;
import org.blog.utils.ResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("message")
public class MessageController {

    @Autowired
    private MessageService messageService;


    @GetMapping("admin/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("admin/message");

        // 根据参数获取message
        List<Message> list = messageService.getMessages(new MessageParam());

        modelAndView.addObject("list", list);
        return modelAndView;
    }

    @GetMapping("delete/{messageId}")
    public void delete(@PathVariable("messageId") Integer messageId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean delete = messageService.delete(messageId);
        if (delete) {
            response.sendRedirect("/message/admin/index");
        } else {
            response.getWriter().println("删除失败");
            response.getWriter().close();
        }
    }


    @PostMapping("search")
    public ModelAndView search( MessageParam param) {
        ModelAndView modelAndView = new ModelAndView("admin/message");
        List<Message> messages = messageService.getMessages(param);

        modelAndView.addObject("list", messages);
        return modelAndView;
    }
}

